import { AMAP_API_KEY } from './amapService';

let loadPromise: Promise<any> | null = null;

export const loadAMapScript = async () => {
  if (typeof window === 'undefined') {
    throw new Error('非浏览器环境无法加载高德地图');
  }

  if ((window as any).AMap) {
    return (window as any).AMap;
  }

  if (loadPromise) {
    return loadPromise;
  }

  loadPromise = new Promise((resolve, reject) => {
    const existingScript = document.getElementById('amap-script') as HTMLScriptElement | null;

    const onLoad = () => {
      if ((window as any).AMap) {
        resolve((window as any).AMap);
      } else {
        loadPromise = null;
        reject(new Error('高德地图脚本加载失败'));
      }
    };

    const onError = () => {
      loadPromise = null;
      reject(new Error('高德地图脚本加载失败'));
    };

    if (existingScript) {
      existingScript.addEventListener('load', onLoad, { once: true });
      existingScript.addEventListener('error', onError, { once: true });
      return;
    }

    const script = document.createElement('script');
    script.id = 'amap-script';
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_API_KEY}`;
    script.async = true;
    script.defer = true;
    script.addEventListener('load', onLoad, { once: true });
    script.addEventListener('error', onError, { once: true });

    document.head.appendChild(script);
  });

  return loadPromise;
};

export const resetAMapLoader = () => {
  loadPromise = null;
};
